import React, { useState, useEffect, useRef } from "react";
import {
  Form,
  Button,
  Input,
  InputNumber,
  TreeSelect,
  Switch,
  Upload,
  message,
} from "antd";
import type { Cate } from "../CateLists/types";
import { fetchCates } from "@/api/cate";
import { fetchItemDetail, updateItem } from "@/api/item";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { useNavigate, useSearchParams } from "react-router-dom";
export default function ItemAdd() {
  const navigate = useNavigate();
  const [cates, setCates] = useState<Cate[]>([]);
  const [searchParams] = useSearchParams();
  // 获取所有商品分类
  const getCates = () => {
    fetchCates().then((res) => {
      if (res.data.code === 200) {
        setCates(res.data.data);
      }
    });
  };
  const formIns = useRef();
  // 获取修改商品 初始数据 设置表单初始值
  const getItemDetail = () => {
    fetchItemDetail(searchParams.get('itemId') as string).then(res => {
      if (res.data.code === 200) {
        formIns.current.setFieldsValue(res.data.data)
        // 手动定义 Upload 和 富文本初始值
        setHtml(res.data.data.content)
        setPics(res.data.data.pics2)
        setFileLists(res.data.data.pics)
      } 
      
    })
  }
  useEffect(() => {
    getCates();
    getItemDetail();
  }, []);
  const submitForm = (params: any) => {
    params = {
      ...params,
      onsale: params.onsale ? 1 : 0,
      pics: pics,
      content: html,
    };
    updateItem(params).then(res => {
      if (res.data.code === 200) {
        message.success(res.data.msg, 2, () => {
          // 回到商品列表
          navigate('/itemLists', {
            replace: true
          })
        })
      } else {
        message.error(res.data.msg)
      }
    })
  };
  const [fileLists, setFileLists] = useState([]);
  const [pics, setPics] = useState<any[]>([]);
  // 文件上传状态发生改变
  const fileStatusChange = (info: any) => {
    setFileLists(info.fileList);
    if (info.file.status === "done" && info.file.response.code === 200) {
      // 拿到图片
      setPics([...pics, info.file.response.data.url]);
    }
  };
  // 富文本相关配置
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const [html, setHtml] = useState("");
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    placeholder: "请输入内容...",
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <Form
      onFinish={submitForm}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      style={{ maxWidth: 600 }}
      ref={formIns}
      initialValues={{ onsale: true }}
    >
      <Form.Item
        label="商品名"
        name="itemName"
        rules={[
          {
            required: true,
            message: "商品名必填",
          },
          {
            pattern: /^\w{2,8}$/,
            message: "2-8位字符组成不能出现特殊字符",
          },
        ]}
      >
        <Input placeholder="请添加商品名" />
      </Form.Item>
      <Form.Item
        label="价格"
        name="price"
        rules={[
          {
            required: true,
            type: "number",
            message: "商品名必填",
          },
        ]}
      >
        <InputNumber min={0} />
      </Form.Item>
      <Form.Item
        label="商品分类"
        name="cateId"
        rules={[
          {
            required: true,
            message: "商品分类必选",
          },
        ]}
      >
        <TreeSelect
          showSearch
          style={{ width: "100%" }}
          dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
          placeholder="请选择分类"
          allowClear
          treeDefaultExpandAll
          fieldNames={{
            label: "cateName",
            value: "id",
          }}
          treeData={cates}
        />
      </Form.Item>
      <Form.Item label="上下架" name="onsale" valuePropName="checked">
        <Switch checkedChildren="上架" unCheckedChildren="下架" />
      </Form.Item>
      <Form.Item label="描述" name="desc">
        <Input.TextArea />
      </Form.Item>
      <Form.Item label="商品图片">
        <Upload
          action="/api/upload"
          name="file"
          fileList={fileLists}
          accept=".jpg, .png, .gif"
          listType="picture-card"
          onChange={fileStatusChange}
        >
          <Button>点击上传</Button>
        </Upload>
      </Form.Item>
      <Form.Item label="商品详情">
        <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            style={{ borderBottom: "1px solid #ccc" }}
          />
          <Editor
            defaultConfig={editorConfig}
            value={html}
            onCreated={setEditor}
            onChange={(editor) => setHtml(editor.getHtml())}
            mode="default"
            style={{ height: "500px", overflowY: "hidden" }}
          />
        </div>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 4 }}>
        <Button htmlType="submit" type="primary">
          提交
        </Button>
        <Button htmlType="submit">重置</Button>
      </Form.Item>
    </Form>
  );
}
